import axios from "axios";
import qs from "qs";
import utils from "./utils";
import { warningNotification, convertToBoolean } from "./utils";
const env = import.meta.env;

// tsconfig.json 允许索引 "suppressImplicitAnyIndexErrors": true,
const CODE_MESSAGE = {
  200: "服务器成功返回请求数据",
  201: "新建或修改数据成功",
  202: "一个请求已经进入后台排队(异步任务)",
  204: "删除数据成功",
  400: "发出信息有误",
  401: "用户没有权限(令牌失效、用户名、密码错误、登录过期)",
  402: "令牌过期",
  403: "用户得到授权，但是访问是被禁止的",
  404: "访问资源不存在",
  406: "请求格式不可得",
  410: "请求资源被永久删除，且不会被看到",
  500: "服务器发生错误",
  502: "网关错误",
  503: "服务不可用，服务器暂时过载或维护",
  504: "网关超时",
};

/**
 * @description 实例化 axios
 */
const instance = axios.create({
  // mock 模式下，url 只能使用相对路径，如果 url 有完整的 http 协议部分则不会被 mock 拦截
  baseURL: convertToBoolean(<string>(<unknown>env.VITE_MOCK_ENABLED))
    ? ""
    : env.VITE_API_URL,
  // baseURL: 'http://localhost:9091/locker',
  // 最长请求时间
  timeout: 10000,
  // crossDomain: true,
  // 跨域是否在请求中协带 cookie
  withCredentials: true,
  headers: {
    // 配后端数据的接收方式application/json;charset=UTF-8 或 application/x-www-form-urlencoded;charset=UTF-8
    // "Content-Type": "application/json;charset=UTF-8",
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
});

// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // config.headers.Test = "special get headers";

    // let token = store.getToken()
    // 	if(token){
    // 		config.headers["lok-token"] = token.token;
    // 	}
    // let ver = store.getAppVer()
    // if(ver){
    // 	config.headers["lok-app-ver"] = ver;
    // }
    return config;
  },
  function (error) {
    utils.errorNotification("请检查 axios 的配置项");
    console.error(
      "Something happened in setting up the request that triggered an Error: ",
      error.message
    );
    // return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    if (response.status != 200) {
      // 不在定义中的返回 undefined
      let msg = CODE_MESSAGE[response.status];
      if (msg != undefined) {
        utils.errorNotification("网络错误：" + msg);
      } else {
        utils.errorNotification("网络错误...");
      }

      console.error(
        "The server responded with a status code: ",
        response.status,
        msg
      );
    } else if (response.status == 200) {
      // 业务状态，不存在
      if (response.data.code !== 200) {
        warningNotification("网络请求错误：" + response.data.code);
        console.warn(
          "The server responded with a business code:",
          response.data.code,
          response.data.message
        );
      }
    }

    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    utils.errorNotification("网络请求错误...");
    console.error(
      "The request was made but no response was received: ",
      error.message
    );
    // return Promise.reject(error);
  }
);

export function get(url: string, params: any) {
  //`params` are the URL parameters to be sent with the request
  return instance.get(url, { params: params });
}

export function post(url: string, data: any) {
  //`data` is the data to be sent as the request body
  // console.log("request post", qs.stringify(data));
  // mock 模式下，数据只能是 json 格式的，否则 mock 参数 options.body 接收不到数据
  let mock = convertToBoolean(<string>(<unknown>env.VITE_MOCK_ENABLED));
  if (mock) {
    return instance.request({ url, method: "post", data: data });
  } else {
    return instance.request({ url, method: "post", data: qs.stringify(data) });
  }
  // return instance.post(url, env.VITE_MOCK_ENABLED ? data : qs.stringify(data));
}

export default instance;
